package com.talent.service.auth.service.wx;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * @ClassName：WxLoginService
 * @Author: hszhou
 * @Date: 2025/1/20 11:06
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Service
public class WxLoginService {
    private static final Logger logger = LoggerFactory.getLogger(WxLoginService.class);

    private final WxProperties properties;

    private final WxMaService wxMaService;

    public WxLoginService(WxProperties properties,WxMaService wxMaService){
        this.properties = properties;
        this.wxMaService = wxMaService;
    }

    public WxMaJscode2SessionResult login(String code){

        if(StringUtils.isEmpty(code)){
            return null;
        }
        try{
            WxMaJscode2SessionResult session = wxMaService.getUserService().getSessionInfo(code);
            logger.info(session.getSessionKey());
            logger.info(session.getOpenid());
            //TODO 可以增加自己的逻辑，关联业务相关数据
            return session;
        }
        catch (WxErrorException e) {
            logger.error(e.getMessage(), e);

            return null;
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
}
